import type { IDeserializable } from "~/models/serialize/IDeserializable";
import { tNum } from "../types";
import { DataType } from "../types/type";
import type { VarDeclare } from "./var_declare";
import { Value } from "../value/Value";

/** 变量初始化：必须包含默认值，否则就不是初始化 */

export class VarInit implements VarDeclare, IDeserializable {

  className: string = 'VarInit';

  constructor(
    public name: string,
    public _type: DataType = tNum,
    public _initial?: Value
  ) {
    if (this._initial === undefined) {
      this._initial = Value.default(_type)
    }
  }

  get type() {
    return this._type;
  }

  set type(t: DataType) {
    // 无初始值不涉及初始值替换
    if (this.inited) {
      // 如果替换的类型兼容原来的类型就不用替换
      if (!t.receiveValue(this.initial)) {
        console.log('初始值被重置为: ', t.default);
        console.log(`因为类型${t.name}不兼容值: `, JSON.parse(JSON.stringify(this._initial)))
        // this._initial!.content = t.default
        this._initial = new Value(t, t.default)
      }
    }
    this._type = t;
  }

  get initial() {
    return this._initial?.content
  }

  set initial(v: any) {
    if (!this.type.receiveValue(v)) {
      console.error(`变量${this.name}初始值修改失败，类型${this.type.name}无法接受值：`, v)
      return
    }
    this._initial = new Value(this.type, v)
  }

  clear() {
    this._initial = undefined
  }

  get inited() {
    return this._initial !== undefined
  }
}